package com.lagou.handler;

import com.alibaba.fastjson.JSONObject;
import com.lagou.common.RpcRequest;
import com.lagou.util.BeanMapUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof RpcRequest){
            RpcRequest rpcRequest = (RpcRequest) msg;
            System.out.println(JSONObject.toJSONString(rpcRequest));
            Object bean = BeanMapUtil.getBean(rpcRequest.getClassName());
            Method[] methods = bean.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (rpcRequest.getMethodName().equals(method.getName())){
                    method.setAccessible(true);
                    Object result = method.invoke(bean, rpcRequest.getParameters());
                    ctx.writeAndFlush(result);
                }
            }
        }
    }
}
